package com.kld.promotion.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.global.EnumList;
import com.kld.common.framework.global.Global;
import com.kld.common.util.DateUtils;
import com.kld.promotion.api.*;
import com.kld.promotion.dao.ActivityDao;
import com.kld.promotion.po.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by 曹不正 on 2016/3/24.
 */
@Service("activtyService")
public class ActivityServiceImpl implements IActivityService {
    private boolean IsPaySkipModel = Global.IsPaySkipModel;
    private Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);

    @Autowired
    private ActivityDao activityDao;


    @Override
    public int deleteByPrimaryKey(BigDecimal id) {
        return activityDao.delete("deleteByPrimaryKey",id);
    }

    @Override
    public int insert(Activity record) {
        return activityDao.insert(record);
    }

    @Override
    public int insertSelective(Activity record) {
        record.setIsdel(BigDecimal.valueOf(0));
        record.setCreatetime(DateUtils.getDate());


        return activityDao.insert("insertSelective",record);
    }

    @Override
    public Activity selectByPrimaryKey(BigDecimal id) {
        return activityDao.get("selectByPrimaryKey",id);
    }

    @Override
    public int updateByPrimaryKeySelective(Activity record) {
        return activityDao.update("updateByPrimaryKeySelective",record);
    }

    @Override
    public int updateByPrimaryKey(Activity record) {
        return activityDao.update("updateByPrimaryKey",record);
    }

    @Override
    public List<Activity> getActList(Map<String, Object> map) {
        return activityDao.find("getActList",map);
    }
    @Override
    public PageInfo getActList(Map<String, Object> map, int PageNum, int PageSize) {
        PageHelper.startPage(PageNum,PageSize);
        List<Actorder> list = activityDao.find("getActList",map);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public int deleteLogicByID(Integer id) {
        Activity activity = new Activity();
        activity.setId(BigDecimal.valueOf(id));
        activity.setIsdel(BigDecimal.valueOf(1));
        return activityDao.update("updateByPrimaryKeySelective",activity);
    }

    @Override
    public List<Prize> getLimitJFActList(Integer num) {
        List<Prize> list = activityDao.find("getLimitJFActList",num);
        return list == null ? new ArrayList<Prize>() : list;
    }

    @Override
    public List<Prize> getJFActList(Map<String, Object> map) {
        return activityDao.find("getJFActList",map);
    }

    @Override
    public List<Activity> getMonthActList(Map<String, Object> stringObjectHashMap) {
        return activityDao.find("getMonthActList",stringObjectHashMap);
    }
    /**
     * 开奖
     *
     * @param idsStr
     * @return
     * @throws Exception
     */
    @Override
    public ResultMsg startAct(String idsStr) throws Exception {
        // TODO: 2016/3/28
//        ResultMsg rmsg = new ResultMsg();
//        String[] idsArr = idsStr.split(",");
//        if (idsArr.length == 0) {
//            rmsg.setResult(false);
//            rmsg.setMsg("请选择奖项！");
//        }
//        List<Integer> idlist = new ArrayList<Integer>();
//        for (String idStr : idsArr) {
//            try {
//                Integer id = Integer.parseInt(idStr);
//                if (id != null) {
//                    idlist.add(id);
//                }
//            } catch (Exception ex) {
//            }
//
//        }
//        if (idlist.size() != idsArr.length) {
//            rmsg.setResult(false);
//            rmsg.setMsg("奖项选择有误");
//            return rmsg;
//        }
//        Actitem actitem = actItemService.selectByPrimaryKey(BigDecimal.valueOf(idlist.get(0)));
//        Activity activity = activityDao.get("selectByPrimaryKey",actitem.getActid());
//
//        List<String> winnerids = actLogService.getMonthWinnerIds(actitem.getActid().intValue());
//
//        //1、获取满足条件的兑换人员订单记录
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("paystarttime", DateUtils.formatDate(activity.getStarttime()));
//        map.put("payendtime", DateUtils.formatDate(activity.getEndtime()));
//        map.put("minpoints", activity.getMinpoints() == null ? "0" : activity.getMinpoints().toString());
//        map.put("filterflag", activity.getFilterflag() == null ? "0" : activity.getFilterflag().toString());
//        map.put("mincount", activity.getMincount() == null ? "0" : activity.getMincount().toString());
//        map.put("outuserids", winnerids);
//
//        List<POrder> orderses = activityDao.get("getMonthActOrdersList",map);
//        List<Integer> newids = new ArrayList<Integer>();
//        if (orderses.size() == 0) {
//            logger.error("抽奖活动！================>人数不足，抽奖活动不完整");
//            throw new Exception("开奖失败。参与人数不足");
//        }
//        for (Iterator<Integer> iter = idlist.iterator(); iter.hasNext(); ) {
//            Integer id = iter.next();
//            Actitem item = actItemService.selectByPrimaryKey(BigDecimal.valueOf(id));
//            if (orderses.size() == 0) {
//                logger.error("抽奖活动！================>人数不足，抽奖活动不完整");
//                break;
//            }
//            for (int i = 0; i < item.getNum().intValue(); i++) {
//                if (orderses.size() == 0) {
//                    logger.error("抽奖活动！================>人数不足，抽奖活动不完整");
//                    break;
//                }
//                Random random = new Random();
//                int r = random.nextInt(orderses.size());
//                POrder order = orderses.get(r);
//                //插入一条中奖记录
//                Actlog actlog = new Actlog();
//                //region 构造抽奖记录
//                actlog.setCreatetime(new Date());
//                actlog.setActid(activity.getId());
//                actlog.setActtype(activity.getType());
//                actlog.setActitemid(item.getId());
//                actlog.setCardno(order.getOilcardno());
//                actlog.setIswon(BigDecimal.valueOf(1));
//                actlog.setPoints(BigDecimal.valueOf(0));
//                actlog.setUserid(order.getUserid());
//                actlog.setUsername(order.getUsername());
//                actlog.setOrderid(BigDecimal.valueOf(order.getId()));
//                actlog.setState(BigDecimal.valueOf(1));   //是否领取
//                //endregion
//                int ri_log = actLogService.insertSelective(actlog);
//                if (ri_log > 0) {
//                    //region 创建活动订单信息
//                    Actorder actorder = new Actorder();
//                    actorder.setCreatetime(new Date());
//                    //根据积分兑换记录，设置中奖用户个人信息
//                    actorder.setOucode(order.getOucode());
//                    actorder.setProvinceid(BigDecimal.valueOf(order.getProvinceid()));
//                    actorder.setCityid(BigDecimal.valueOf(order.getCityid()));
//                    actorder.setCountyid(BigDecimal.valueOf(order.getCountyid()));
//                    actorder.setTownid(BigDecimal.valueOf(order.getTownid()));
//                    actorder.setZip(order.getZip());
//                    actorder.setAddress(order.getAddress());
//                    actorder.setPhone(order.getPhone());
//                    actorder.setUserid(order.getUserid());
//                    actorder.setRealname(order.getRealname());
//                    actorder.setCardno(order.getOilcardno());
//                    //中奖信息
//                    actorder.setActid(actlog.getActid());
//                    actorder.setActitemid(actlog.getActitemid());
//                    actorder.setActtype(actlog.getActtype());
//                    actorder.setPoints(BigDecimal.valueOf(0));
//                    actorder.setState(BigDecimal.valueOf(1));  //订单状态：未发货
//                    actorder.setActlogid(actlog.getId());
//                    int ii = actOrderService.insertSelective(actorder);
//                    if (ii > 0) {
//
//                    } else {
//                        logger.error("抽奖失败！================>移除中奖记录失败");
//                        throw new Exception("抽奖失败！");
//                    }
//                    //endregion
//                    //region 移除中奖名单
//                    int rw = removeWinActOrders(orderses, order.getUserid());
//                    if (rw == 0) {
//                        logger.error("抽奖失败！================>移除中奖记录失败");
//                        throw new Exception("抽奖失败！");
//
//                    }
//                    newids.add(id);
//
//                    //endregion
//                } else {
//                    logger.error("抽奖失败！================>添加抽奖记录失败");
//                    throw new Exception("抽奖失败！");
//                }
//            }
//        }
//        if (newids.size() > 0) {
//            if (newids.size() < idlist.size()) {
//                activity.setOpenstate(new BigDecimal(EnumList.MonthActOpenState.Openning.value));
//                int upd_act = updateByPrimaryKeySelective(activity);
//                if (upd_act > 0) {
//
//                } else {
//                    logger.error("更新月抽奖活动开奖状态失败========");
//                    throw new Exception("开奖失败");
//                }
//            }
//
//            int upd = actItemService.openActItem(newids);
//            if (upd > 0) {
//                rmsg.setResult(true);
//                rmsg.setMsg("开奖成功");
//            } else {
//                throw new Exception("开奖失败");
//            }
//        } else {
//            rmsg.setResult(false);
//            rmsg.setMsg("开奖失败！参与人员不足");
//        }

        return null;
    }

    @Override
    public Integer editFilter(Integer actid, Integer minpoints, Integer mincount, Integer filterlogic) {
        Activity activity = selectByPrimaryKey(BigDecimal.valueOf(actid));
        if (activity == null) {
            return -1;
        }
        activity.setMincount(BigDecimal.valueOf(mincount));
        activity.setMinpoints(BigDecimal.valueOf(minpoints));
        activity.setFilterflag(BigDecimal.valueOf(filterlogic));
        return updateByPrimaryKeySelective(activity);

    }

    @Override
    public List<Activity> getActListByType(Integer type) {
        return activityDao.find("getActListByType",type);
    }

    @Override
    public List<Activity> getActListByType_1(Integer type, Date currTime, Integer flag) {
        return activityDao.getActListByType_1(type,currTime,flag);
    }

    @Override
    public List<Activity> getActListByPid(BigDecimal pid, Date startdate, Date enddate) {
        return activityDao.getActListByPid(pid,startdate,enddate);
    }

    @Override
    public List<PrizeInfo> queryPrizesByUserId(String userid, Integer num, Integer state, Integer acttype) {
        return activityDao.queryPrizesByUserId(userid,num,state,acttype);
    }

    @Override
    public List<Activity> getActListByEndtime(Date currentTime) {
        return activityDao.find("getActListByEndtime",currentTime);
    }

    @Override
    public Integer queryActTimesByUserID(String userID) {
        Integer restNum = activityDao.get("queryActTimesByUserID",userID);
        return restNum == null ? 0 : restNum;
    }

    /**
     * 砸金蛋，逻辑复杂的后面做。
     * @param userID
     * @param userName
     * @param channel
     * @return
     * @throws Exception
     */
    @Override
    public ResultMsg smashingEggs(String userID, String userName, Integer channel) throws Exception {
        return null;
        // TODO: 2016/3/24
    }

    @Override
    public boolean checkTitleIfUsed(String title) {
        return (int)activityDao.get("checkTitleIfUsed",title) > 0 ? true : false;
    }

    /**
     * 发布活动（带事务）
     *
     * @param actid
     * @return
     * @throws Exception
     */
    @Override
    public ResultMsg publishAct(Integer actid) throws Exception {
        // TODO: 2016/3/24  
        return null;
    }
    /**
     * 发布月抽奖获奖者名单
     *
     * @param actid
     * @return
     * @throws Exception
     */
    @Override
    public ResultMsg publishMonthWinner(Integer actid) throws Exception {
        // TODO: 2016/3/24  
        return null;
    }

    /**
     * 生成月活动
     *
     * @param pact
     * @return
     * @throws Exception
     */
    @Override
    public ResultMsg taskGenerateMonthAct(Activity pact) throws Exception {
        // TODO: 2016/3/24  
        return null;
    }

    @Override
    public BigDecimal getPointsById(BigDecimal id) {
        return activityDao.get("getPointsById",id);
    }

    /**
     * 带事务，编辑act
     * @param actid
     * @return
     * @throws Exception
     */
    @Override
    public ResultMsg endAct(Integer actid) throws Exception {
       return null;
        // TODO: 2016/3/24  
    }
    /**
     * 抽奖
     * 1、按活动概率抽奖（抽中以后进行成本判断，亏损认为未抽中）
     * 2、如果中奖，插入抽奖记录
     * 3、支付积分（参数uniqueid 规则：11+actlogid ），若支付失败throw 异常，事务自动回滚
     *
     * @param actID
     * @param userID
     * @param userName
     * @param cardNo
     * @return
     */
    @Override
    public ResultMsg payPointsAct(BigDecimal actID, String userID, String userName, String cardNo, EnumList.Channel channel) throws Exception {
        return null;
        // TODO: 2016/3/24  
    }

    @Override
    public String getAddress(String alias) {
        return activityDao.get("getAddress",alias);
    }

    @Override
    public List<Activity> getActListByState(Integer state) {
        return activityDao.find("getActListByState",state);
    }

    @Override
    public Integer updateStateToLaunching(Integer state, Date currDate, Integer id) {
        return activityDao.updateStateToLaunching(state, currDate, id);
    }

    @Override
    public Integer finishActivity(Integer state, Date currentTime, Integer id) {
        return activityDao.finishActivity(state, currentTime, id);
    }
    //获取首页展示活动商品列表
    @Override
    public List<Activity> getIndexActProList(Integer limit) {
        // TODO: 2016/3/24
        return null;
    }
}
